/* 
 * Jquery 自动完成插件简单版
 */
define(function (require, exports, module)
{
  var $ = require('jq_ext');
  var jxbaseinfo = require('jxbaseinfo');
  var cryptojs = require('crypto-js');
  var ws ;
  var wsTime = new Date().getTime();
  var wsid;
  var wsConfig ;
  var $websocket =
  {
    //  默认配置
    defaults: {
      host:window.location.hostname,
      port:window.location.port,
      webpath:jxbaseinfo.path,
      // url
      url: '',
      onopen:null,
      onclose:null,
      onerror:null,
      onmessage :null,
      testTime:30000,
    },
		no:0,
    openFlag:false,
    loginFlag:false,
    logoutFlag:false,
    isOpen:function()
    {
      return this.openFlag ;
    },
    isLogin:function()
    {
      return this.loginFlag;
    },
    isLogout:function()
    {
      return this.logoutFlag;
    },    
    init: function (config)
    {
      wsConfig = $.extend({}, this.defaults, config);
      wsid = setInterval(wsTest,wsConfig.testTime);
      wsInit() ;
    },
    /**
     * 警告
     * @param   {String, HTMLElement}   消息内容
     * @param   {Function}              (可选) 回调函数
     */
    send: function (type,data)
    {
      var message = {} ;
      this.no ++ ;
      message["no"] = this.no;
      message["type"] = type ;
      message["token"] = $.cookie('JX_LOGIN_SESSION');
      message["time"] = new Date().getTime();
      message["data"] = data ;
      var md5Str = message.no + "" + message.time  + ""+ type+data + message.token;
      message["md5"] = cryptojs.MD5(md5Str).toString();
      $.log(message);
      ws.send(JSON.stringify(message)) ;
    }
  }
  
  function wsMessage(type)
  {
    $websocket.send(type,"") ;
  }
  
  function wsLogin()
  {
    wsMessage('WS_LOGIN') ;
  }
  
  function wsTest()
  {
    if ((!$websocket.isOpen()) || (!$websocket.isLogin()))
      return ;
    if (new Date().getTime() - wsTime <wsConfig.testTime - 50)
      return ;
    wsMessage("WS_TEST","") ;
  }
  
  function wsInit()
  {
    if ($websocket.isLogout())
    {
      clearInterval(wsid) ;
      return ;
    }
    var protocol = location.protocol === 'https' ? 'wss://' : 'ws://';
  
      ws = new WebSocket(protocol + wsConfig.host + ":" + wsConfig.port + wsConfig.webpath + "ws/" + wsConfig.url );
      
      ws.onopen = function()
			{
				$websocket.openFlag = true ;
				if (null != wsConfig.onopen)
					wsConfig.onopen() ;
				wsLogin() ;
			};
      ws.onclose = function()
			{
				$websocket.openFlag = false ;
        $websocket.loginFlag = false ;
				if (null != wsConfig.onclose)
					wsConfig.onclose() ;
        
        setTimeout(wsInit,wsConfig.testTime);
			};
      ws.onmessage = function(evt) 
      {
        wsTime = new Date().getTime();
        var msg = JSON.parse(evt.data) ;
        if ((msg.type == "WS_LOGIN_RESULT") && (msg.result == "0"))
        {
          $websocket.loginFlag = true ;
        }
        else if ((msg.type == "WS_LOGIN_RESULT") && (msg.result != "0"))
        {
          $websocket.loginFlag = false ;
          $websocket.logoutFlag = true ;
        }
        
        if (msg.type == "WS_LOGOUT")
        {
          $websocket.logoutFlag = true ;
        }
        if (wsConfig.onmessage != null)
          wsConfig.onmessage(evt,msg);
      };
      ws.onerror = function(){
				$websocket.openFlag = false ;
        $websocket.loginFlag = false ;        
				if (null != wsConfig.onerror)
					wsConfig.onerror() ;
				setTimeout(wsInit,wsConfig.testTime);
			};
  }
  return $websocket;
});